// Keys.
export const TOKEN = 'TOKEN' //用户token

/** Class storage provider. */
class StorageProvider {
  private namespace: string
  private provider: Storage

  /**
   * Create a private provider.
   * @param {String} namespace
   * @param {Storage} provider
   */
  constructor(namespace: string, provider: Storage) {
    this.namespace = namespace
    this.provider = provider
  }

  getItem(key: string) {
    const k = this.scopeKey(key)
    const v = this.provider.getItem(k)
    try {
      return v ? JSON.parse(v) : null
    } catch {
      return null
    }
  }

  setItem(key: string, value: unknown) {
    const k = this.scopeKey(key)
    this.provider.setItem(k, JSON.stringify(value))
  }

  removeItem(key: string) {
    const k = this.scopeKey(key)
    this.provider.removeItem(k)
  }

  clear() {
    let index = 0
    const removeKeys = []
    while (index > -1) {
      const key = this.provider.key(index)
      if (key) {
        if (key.indexOf(this.namespace) !== -1) {
          removeKeys.push(key)
        }
        index++
      } else {
        index = -1
      }
    }
    removeKeys.forEach((key) => {
      this.provider.removeItem(key)
    })
  }

  private scopeKey(key: string) {
    return `${this.namespace}_${key}`
  }
}

export const local = new StorageProvider('AVATR_CHARGE', window.localStorage)

export const session = new StorageProvider('AVATR_CHARGE', window.sessionStorage)
